<template>
  <div id="traj-graph"></div>
</template>

<script setup>
import * as echarts from "echarts";
import "echarts-gl";
import { onMounted, onBeforeUnmount, ref, onUpdated } from "vue";

// 通过props接收图表数据
const props = defineProps({
  chartData: {
    type: Array,
    required: true,
  },
});

const chartInstance = ref(null);

onMounted(() => {
  initChart();
});

onBeforeUnmount(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    chartInstance.value = null;
  }
});

onUpdated(() => {
  setData();
});

const setData = () => {
  if (chartInstance.value === null) return;

  const option = {
    legend: {
      data: props.chartData.map((data, index) => data.name),
      orient: 'horizontal',
      left: 'left'
    },
    backgroundColor: "#ddd",
    tooltip: {
      trigger: "item",
    },
    grid3D: {
      boxWidth: 300,
      boxHeight: 150,
      boxDepth: 300,
      viewControl: {
        distance: 300,
      },
    },
    xAxis3D: {
      type: "value",
      min: -15,
      max: 15,
    },
    yAxis3D: {
      type: "value",
      min: -8,
      max: 8,
    },
    zAxis3D: {
      type: "value",
      min: 0,
      max: 3,
    },
    series: props.chartData.map((data, index) => {
      return {
        type: "line3D",
        data: data.points,
        name: data.name,
      };
    }),
  };
  chartInstance.value.setOption(option);
};

const initChart = () => {
  const chartDom = document.getElementById("traj-graph");
  if (chartDom) {
    chartInstance.value = echarts.init(chartDom);
    setData();
  }
};
</script>

<style scoped></style>
